package org.lanqiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lanqiao.dto.SetmealDto;
import org.lanqiao.entity.Category;
import org.lanqiao.entity.Setmeal;
import org.lanqiao.entity.SetmealDish;
import org.lanqiao.service.CategoryService;
import org.lanqiao.service.SetmealDishService;
import org.lanqiao.service.SetmealService;
import org.lanqiao.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return Result.success("添加套餐成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page , int pageSize , String name){
        //创建分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page , pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(name != null , "name" , name);
        //将查询到的套餐信息分页
        setmealService.page(pageInfo , queryWrapper);

        BeanUtils.copyProperties(pageInfo , setmealDtoPage , "records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal record : records) {
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(record , setmealDto);
            Long categoryId = record.getCategoryId();
            //根据菜品的id查找菜品分类名称
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String name1 = category.getName();
                setmealDto.setCategoryName(name1);
            }
            setmealDtos.add(setmealDto);
        }
        setmealDtoPage.setRecords(setmealDtos);

        return Result.success(setmealDtoPage);

    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> deleteSetmealByIds(@RequestParam List<Long> ids){
         setmealService.deleteSetmealAndSetmealDish(ids);
         return Result.success("删除套餐成功");

    }
}
